package com.intexh.speedandroid.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.StrictMode;

import com.intexh.speedandroid.BuildConfig;
import com.intexh.speedandroid.helper.MyActivityLifecycle;
import com.intexh.speedandroid.helper.PickerHelper;
import com.intexh.speedandroid.helper.UserHelper;
import com.intexh.speedandroid.net.NetworkManager;
import com.mob.MobSDK;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by FrankZhang on 2017/11/14.
 */

public class MainApplication extends Application {

    private final static ArrayList<BaseActivity> activitys = new ArrayList<>();
    private final static ArrayList<Activity> tempActivitys = new ArrayList<>(); //临时记录activity界面
    private final static ArrayList<Activity> webActivityList = new ArrayList<>();
    private static MainApplication instance;
    private static MyActivityLifecycle myActivityLifecycle;

    // 创建一个单线程的线程池。
    // 用于写入数据库
    public static ExecutorService persistenceExecutorService = Executors
            .newSingleThreadExecutor();
    private ExecutorService multiThreadExecutorService;


    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        myActivityLifecycle = new MyActivityLifecycle();
        registerActivityLifecycleCallbacks(myActivityLifecycle);    //监听activity生命周期

//        MultiDex.install(this);
        if(!BuildConfig.IS_DEBUG){  //非debug模式 初始化异常捕捉
            CrashReport.initCrashReport(getApplicationContext(), BuildConfig.BUGLY_APP_ID, BuildConfig.IS_DEBUG);
        }
        NetworkManager.INSTANCE.init(this); //初始化网络请求
		MobSDK.init(this);
        PickerHelper.INSTANCE.init(this);
//        initJPush();
    }


    public static MainApplication getInstance() {
        return instance;
    }
    public static Context getAppContext() {
        return instance.getApplicationContext();
    }

    //64k 分包
//    @Override
//    protected void attachBaseContext(Context base) {
//        super.attachBaseContext(base);
//        MultiDex.install(this);
//    }

//    private void initJPush() {
//        JPushHelper.init(this);
//        if(UserHelper.isLogin()){
//            if(UserHelper.isLogin()){
//                JPushHelper.setAlias(UserHelper.getUser().getPush_id());
//            }
//        }
//    }




    /**
     * 判断前台后台运行
     * @return  true  处于后台   false  前台
     */
    public static boolean isAppBackground() {
        if (myActivityLifecycle.getStartCount() == 0) {
            return true;
        }
        return false;
    }


    /**
     * 显示登录凭证失效弹窗提醒在当前显示的界面上
     */
    public static void showTokenInvalidHint(){
        BaseActivity activity = activitys.get(activitys.size()==0?0:activitys.size() - 1);
        UserHelper.loginOut();
        activity.showTokenInvalidHintDialog();
    }

    //全局记录activity
    public static void addActivity(BaseActivity context) {
        activitys.add(context);
    }
    public static void removeActivity(BaseActivity context) {
        activitys.remove(context);
    }
    public static void finishAllActivity() {
        Activity activity;
        for (int i = activitys.size() - 1; i >= 0; i--) {
            activity = activitys.get(i);
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    //临时记录activity
    public static void addTempActivity(Activity context) {
        tempActivitys.add(context);
    }
    public static void removeTempActivity(Activity context) {
        tempActivitys.remove(context);
    }
    public static void finishAllTempActivity() {
        Activity activity;
        for (int i = tempActivitys.size() - 1; i >= 0; i--) {
            activity = tempActivitys.get(i);
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    //网页记录activity
    public static void addWebActivity(Activity context) { //记录打开的activity
        webActivityList.add(context);
    }
    public static void removeWebActivity(Activity key) {
        webActivityList.remove(key);
    }
    public static void finishAllWebActivity() {
        Activity activity;
        for (int i = webActivityList.size() - 1; i >= 0; i--) {
            activity = webActivityList.get(i);
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
        }
    }


    /**
    * 线程池用于保存数据库
     */
    public ExecutorService getExecutor(int size) {
        if (size <= 1) {
            return persistenceExecutorService;
        } else {
            if (multiThreadExecutorService == null) {
                multiThreadExecutorService = Executors.newFixedThreadPool(5);
            }
            return Executors.newFixedThreadPool(5);
        }
    }

    /**
     * 载入调试设置 严苛模式检查
     */
    private void initDebugSetting() {
        if (BuildConfig.IS_DEBUG) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectCustomSlowCalls() //API等级11，检查代码执行缓慢
//                    .detectDiskReads()        //磁盘读写检查
//                    .detectDiskWrites()
//                    .detectNetwork()   // or .detectAll() for all detectable problems
                    .penaltyDialog() //弹出违规提示对话框
                    .penaltyLog() //在Logcat 中打印违规异常信息
//                    .penaltyFlashScreen() //API等级11 会造成屏幕闪烁，不过一般的设备可能没有这个功能。
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
//                    .detectLeakedSqlLiteObjects()   //用来检查 SQLiteCursor 或者 其他 SQLite对象是否被正确关闭
                    .detectLeakedClosableObjects() //API等级11    用于资源没有正确关闭时提醒
                    .detectActivityLeaks()      //activity 内存泄漏检测
                    .penaltyLog()
//                    .penaltyDeath()     //当触发违规条件时，直接Crash掉当前应用程序。
                    .build());
        }
    }
}
